<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{ height: '100%' }" :style="{ height: '100%' }">
      <a-card-grid style="width:25%;textAlign:'center';height:100%">
        <div style="height:100%">
          <a-input-search style="margin-bottom: 8px" v-model="searchValue" placeholder="请输入组织名称查询" @change="onTreeSearchChange" />
          <div>
            <div class="hh-scroll-hover" style="height:460px">
              <div>
                <a-tree
                  showLine
                  @expand="onExpand"
                  :expandedKeys="expandedKeys"
                  :selectedKeys="selectedKeys"
                  :autoExpandParent="autoExpandParent"
                  :treeData="orgList"
                  draggable
                  @dragenter="onDragEnter"
                  @drop="onDrop"
                  @select="this.onOrgTreeSelect"
                >
                  <template slot="title" slot-scope="{title}">
                    <span v-if="title.indexOf(searchValue) > -1">
                      {{ title.substr(0, title.indexOf(searchValue)) }}
                      <span class="search-tree-color">{{ searchValue }}</span>
                      {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span v-else>{{ title }}</span>
                  </template>
                </a-tree>
              </div>
            </div>
          </div>
        </div>
      </a-card-grid>
      <a-card-grid style="width:75%;textAlign:'center';height:100%">
        <div>
          <a-tabs defaultActiveKey="baseInfo" @change="tabsChange">
            <a-tab-pane tab="基础信息" key="baseInfo" forceRender>
              
            </a-tab-pane>
            <a-tab-pane tab="角色权限列表" key="roleList" forceRender>
              
            </a-tab-pane>
            <a-tab-pane tab="用户权限列表" key="userList" forceRender>
              
            </a-tab-pane>
            
          </a-tabs>
          <div v-if="tabKey==='baseInfo'" class="hh-scroll-hover" style="height:400px;">
            <org-form ref="orgPage" />
          </div>
          <div  v-if="tabKey==='roleList'">
            <div class="table-page-search-wrapper">
              <a-form layout="horizontal" >
                <a-row :gutter="8">
                  <a-col :md="9" :sm="24">
                    <a-form-item label="角色名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-model="queryRoleParam.roleName" placeholder="支持模糊查询"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="9" :sm="24">
                    <a-form-item label="角色类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-select v-model="queryRoleParam.roleTypes" mode="multiple" placeholder="请选择" allowClear >
                        <a-select-option v-for="item in dictData.roleType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } ">
                      <a-button type="primary" @click="() =>{this.findRoleListBtn()}">查询</a-button>
                      <a-button style="margin-left: 8px" @click="() => {this.clearRoleAll()}">重置</a-button>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <vxe-grid
              class="vxe-table-antd"
              resizable
              show-overflow
              ref="roleListTable"
              stripe
              border
              highlight-hover-row
              highlight-current-row
              highlight-hover-column
              highlight-current-column
              highlight-cell
              height="376px"
              size="small"
              row-id="roleId"
              :columns="roleColumn"
              :data="roleTableData"
              :loading="roleLoading"
              :start-index="(roleTablePage.currentPage - 1) * roleTablePage.pageSize"
              :pager-config="roleTablePage"
              @page-change="handleRolePageChange"
            >
            </vxe-grid>
          </div>
          <div  v-if="tabKey==='userList'">
            <div class="table-page-search-wrapper">
              <a-form layout="horizontal" >
                <a-row :gutter="8">
                  <a-col :md="9" :sm="24">
                    <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-model="queryUserParam.userName" placeholder="支持模糊查询"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="9" :sm="24">
                    <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-model="queryUserParam.fullName" placeholder="支持模糊查询"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } ">
                      <a-button type="primary" @click="() =>{this.findUserListBtn()}">查询</a-button>
                      <a-button style="margin-left: 8px" @click="() => {this.clearUserAll()}">重置</a-button>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <vxe-grid
              class="vxe-table-antd"
              resizable
              show-overflow
              ref="userListTable"
              stripe
              border
              highlight-hover-row
              highlight-current-row
              highlight-hover-column
              highlight-current-column
              highlight-cell
              height="376px"
              size="small"
              row-id="userId"
              :columns="userColumn"
              :data="userTableData"
              :loading="userLoading"
              :start-index="(userTablePage.currentPage - 1) * userTablePage.pageSize"
              :pager-config="userTablePage"
              @page-change="handleUserPageChange"
              :checkbox-config="{reserve: true, checkMethod}"
            >
            </vxe-grid>
          </div>
        </div>
      </a-card-grid>
      <a-modal
        title="角色授权"
        centered
        style="top: 20px;"
        width="60%"
        destroyOnClose
        v-model="roleVisible"
        cancelText="关闭"
        okText="保存"
        @ok="saveRole"
      >
        <role-transfer-form ref="roleTransferPage" />
      </a-modal>
      <a-modal
        title="单独添加用户"
        centered
        style="top: 20px;"
        width="85%"
        destroyOnClose
        v-model="orgUservisible"
        cancelText="关闭"
        okText="保存"
        @ok="saveUser"
      >
        <org-user-form ref="orgUserPage" :orgInfo="orgInfo" />
      </a-modal>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="plus" @click="() =>{this.orgAdd()}">同级新增</a-button>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="plus-circle" @click="() =>{this.childOrgAdd()}">子级新增</a-button>
      <a-button style="margin-left: 8px;" v-if="infoFlag" type="primary" icon="edit" @click="() =>{this.saveOrg()}">保存</a-button>
      <a-button style="margin-left: 8px" v-if="infoFlag" type="danger" icon="minus" @click="() =>{this.deleteOrg()}">删除</a-button>
      <a-button
        style="margin-left: 8px"
        ghost
        v-if="infoFlag"
        type="primary"
        icon="minus-circle"
        @click="() =>{this.clearOrgCache()}">清除缓存</a-button>
      <a-button style="margin-left: 8px;" v-if="roleFlag" type="primary" icon="plus" @click="() =>{this.openRoleModel()}">授权</a-button>
      <a-button style="margin-left: 8px;" v-if="userFlag" type="primary" icon="plus" @click="() =>{this.openOrgUserModel()}">添加用户</a-button>
      <a-button style="margin-left: 8px" v-if="userFlag" type="danger" icon="minus" @click="() =>{this.deleteUser()}">删除用户</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import { getBatchDict,getOrgTreeList, getOrgDetail, getOrgUserList, addOrg, editOrg, deleteOrg, moveOrg, clearOrgCache, getOrgRoleList, getOrgRoleInfo, saveOrgRole, saveOrgUser, deleteOrgUser } from "@/services/system/api"
import FooterToolBar from '@/components/FooterToolbar'
import OrgForm from '@/pages/system/form/OrgForm'
import RoleTransferForm from '@/pages/system/form/RoleTransferForm'
import OrgUserForm from '@/pages/system/form/OrgUserForm'
import modal from 'ant-design-vue/es/modal'
import { loop, loopParentKey } from '@/utils/util'
const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'processing',
    text: '启用'
  }
}

export default {
  name: 'OrgManager',
  components: {
    FooterToolBar,
    OrgForm,
    RoleTransferForm,
    OrgUserForm
  },
  data () {
    return {
      description: '组织管理',
      dictData: {},
      tabKey:'baseInfo',
      // 角色授权
      roleVisible: false,
      orgUservisible: false,
      // 用户查询条件
      queryUserParam: {},
      // 角色查询条件
      queryRoleParam: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      // 基础信息操作按钮是否显示
      infoFlag: true,
      orgInfo: null,
      // 角色列表操作按钮是否显示
      roleFlag: false,
      // 用户列表操作按钮是否显示
      userFlag: false,
      // 组织树
      expandedKeys: [],
      selectedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      orgList: [],
      infoButtonType: '9',
      // 角色列表参数
      roleTableData: [],
      roleLoading: false,
      roleTablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      roleColumn: [
        { type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'roleId', title: '角色Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'roleName', title: '角色名称', align: 'center', fixed: 'left', width: 200 },
        { field: 'parentId', title: '父角色Id', visible: false, align: 'center', width: 200 },
        { field: 'roleType', title: '角色类型', visible: false, align: 'center', width: 100 },
        { field: 'roleTypeName', title: '角色类型', align: 'center', width: 100 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250 }
      ],
      // 用户列表参数
      userTableData: [],
      userLoading: false,
      userTablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      userColumn: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        { type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'userId', title: '用户Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'userName', title: '用户名', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', width: 150 },
        { field: 'privilegeSource', title: '授权来源ID', visible: false, align: 'center', width: 150 },
        { field: 'sourceName', title: '授权来源', align: 'center', width: 150 },
        { field: 'userType', title: '用户类型key', visible: false, align: 'center', width: 150 },
        { field: 'userTypeName', title: '用户类型', align: 'center', width: 150 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } }
      ]
    }
  },
  created () {
    // 初始化数据
    this.findOrgTreeList()
    const params = {}
    params.dictFields = 'roleType'
    this.$http.post(getBatchDict,params).then(res => {
      this.dictData = res.result
    })
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  methods: {
    // 树节点选择事件
    onOrgTreeSelect (selectedKeys) {
      this.infoButtonType = '3'
      this.selectedKeys = selectedKeys
      if (selectedKeys && selectedKeys.length > 0) {
        this.findOrgInfo()
        if (this.roleFlag) {
          this.findRoleList()
        }
        if (this.userFlag) {
          this.findUserList()
        }
      }
    },
    findOrgInfo () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        const orgId = this.selectedKeys[0]
        // 获取节点相关信息
        const params = {}
        params.orgId = orgId
        setTimeout(() => {
          this.$http.post(getOrgDetail,params).then((res) => {
            this.orgInfo = res.result
            // 赋值子组件信息
            this.$refs.orgPage.setInitDate(res.result)
          }).catch(() => {
          })
        }, 50)
      }
    },
    findUserListBtn () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.roleTablePage.pageNum = 1
        this.roleTablePage.currentPage = 1
        this.findUserList()
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    findUserList () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.userloading = true
        const params = Object.assign(this.queryUserParam, this.userTablePage)
        params.orgId = this.selectedKeys[0]
        this.$http.post(getOrgUserList,params).then((res) => {
          this.userTableData = res.result.list
          this.userTablePage.total = res.result.total
          this.userTablePage.pageNum = res.result.pageNum
          this.userTablePage.currentPage = res.result.pageNum
          this.userTablePage.pageSize = res.result.pageSize
          this.userLoading = false
        }).catch(() => {
          this.userLoading = false
        })
      }
    },
    findRoleListBtn () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.roleTablePage.pageNum = 1
        this.roleTablePage.currentPage = 1
        this.findRoleList()
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    findRoleList () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.roleloading = true
        const params = Object.assign(this.queryRoleParam, this.roleTablePage)
        params.orgId = this.selectedKeys[0]
        this.$http.post(getOrgRoleList,params).then((res) => {
          this.roleTableData = res.result.list
          this.roleTablePage.total = res.result.total
          this.roleTablePage.pageNum = res.result.pageNum
          this.roleTablePage.currentPage = res.result.pageNum
          this.roleTablePage.pageSize = res.result.pageSize
          this.roleLoading = false
        }).catch(() => {
          this.roleLoading = false
        })
      }
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onTreeSearchChange (e) {
      const value = e.target.value
      if (value) {
        const data = [...this.orgList]
        const expandedKeys = []
        loopParentKey(data, value, expandedKeys)
        this.expandedKeys = expandedKeys
        this.searchValue = value
        this.autoExpandParent = true
      }
    },
    tabsChange (key) {
      this.tabKey=key
      if (key === 'baseInfo') {
        this.findOrgInfo()
        this.infoFlag = true
        this.roleFlag = false
        this.userFlag = false
      } else if (key === 'roleList') {
        this.findRoleList()
        this.infoFlag = false
        this.roleFlag = true
        this.userFlag = false
      } else if (key === 'userList') {
        this.findUserList()
        this.infoFlag = false
        this.roleFlag = false
        this.userFlag = true
      }
    },
    findOrgTreeList () {
      const params = {}
      params.searchText = this.searchValue
      setTimeout(() => {
        this.$http.post(getOrgTreeList,params).then((res) => {
          this.orgList = res.result.orgList
          this.expandedKeys = res.result.expandedKeys
        }).catch(() => {
        })
      }, 50)
    },
    formatStatus (cellValue) {
      if (cellValue) {
        const text = statusMap[cellValue].text
        const status = statusMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    saveOrg () {
      // 表单验证
      const { $refs: { orgPage } } = this
      const orgForm = new Promise((resolve, reject) => {
        orgPage.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      this.errors = []
      Promise.all([orgForm]).then(values => {
        if (values && values.length > 0) {
          const org = values[0]
          if (org.orgId) {
            setTimeout(() => {
              this.$http.post(editOrg,org).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                let oldTitle = ''
                if (this.orgInfo) {
                  oldTitle = this.orgInfo.orgName
                }
                // 更新树节点
                if (oldTitle !== res.result.orgName) {
                  const dragKey = res.result.orgId
                  const data = [...this.orgList]
                  let dragObj
                  let ar
                  let i
                  loop(data, dragKey, (item, index, arr) => {
                    ar = arr
                    i = index
                    dragObj = item
                  })
                  dragObj.title = res.result.orgName
                  dragObj.value = res.result.orgName
                  ar.splice(i, 1, dragObj)
                  this.orgList = data
                  this.orgInfo = res.result
                  const newSelect = []
                  newSelect.push(dragKey)
                  this.selectedKeys = newSelect
                  orgPage.getOrgTreeByType()
                  orgPage.getOrgSelectTree()
                }
              }).catch(() => {
                // this.$refs.orgPage.setInitDate(this.orgInfo)
              })
            }, 50)
          } else {
            setTimeout(() => {
              this.$http.post(addOrg,org).then((res) => {
                modal.info({ title: '成功提示', content: '新增成功' })
                const orgId = res.result.orgId
                if (this.infoButtonType === '9') {
                  this.findOrgTreeList()
                  const newSelect = []
                  newSelect.push(orgId)
                  this.selectedKeys = newSelect
                  this.orgInfo = res.result
                  return
                }
                const data = [...this.orgList]
                const dragKey = this.orgInfo.orgId
                const dropKey = res.result.parentId
                const dragObj = {}
                dragObj.key = orgId
                dragObj.title = res.result.orgName
                dragObj.value = res.result.orgName
                dragObj.parentKey = res.result.parentId
                dragObj.icon = res.result.icon
                dragObj.scopedSlots = { title: 'title' }
                if (this.infoButtonType === '1') {
                  // 同级新增
                  let ar
                  let i
                  loop(data, dragKey, (item, index, arr) => {
                    ar = arr
                    i = index
                  })
                  ar.splice(i, 0, dragObj)
                } else if (this.infoButtonType === '2') {
                  // 子级新增
                  loop(data, dropKey, item => {
                    item.children = item.children || []
                    if (!item.expanded) {
                      item.expanded = true
                    }
                    // where to insert 示例添加到尾部，可以是随意位置
                    item.children.push(dragObj)
                  })
                }
                this.orgList = data
                this.$refs.orgPage.setInitDate(res.result)
                const newSelect = []
                newSelect.push(orgId)
                this.selectedKeys = newSelect
                this.orgInfo = res.result
                const newExpandedKeys = this.expandedKeys
                if (newExpandedKeys && newExpandedKeys.length > 0) {
                  if (newExpandedKeys.indexOf(dropKey) <= 0) {
                    newExpandedKeys.push(dropKey)
                    this.expandedKeys = newExpandedKeys
                  }
                }
                orgPage.getOrgTreeByType()
                orgPage.getOrgSelectTree()
              }).catch(() => {
              })
            }, 50)
          }
        }
      }).catch(() => {
        const errors = Object.assign({}, orgPage.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    orgAdd () {
      if (this.orgInfo) {
        this.infoButtonType = '1'
        const params = {}
        params.parentId = this.orgInfo.parentId
        params.parentCode = this.orgInfo.parentCode
        params.parentName = this.orgInfo.parentName
        params.icon = this.orgInfo.icon
        params.orgId = ''
        params.orderNo = this.orgInfo.orderNo
        params.rate = this.orgInfo.rate
        this.$refs.orgPage.setInitDate(params)
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    childOrgAdd () {
      if (this.orgInfo) {
        this.infoButtonType = '2'
        const params = {}
        params.parentId = this.orgInfo.orgId
        params.parentCode = this.orgInfo.orgCode
        params.parentName = this.orgInfo.orgName
        params.icon = this.orgInfo.icon
        params.orgId = ''
        params.orderNo = ''
        let rate = this.orgInfo.rate
        if (rate) {
          rate = rate + 1
        } else {
          rate = 1
        }
        params.rate = rate
        this.$refs.orgPage.setInitDate(params)
      } else {
        modal.warn({ title: '提示', content: '请先选择某一节点' })
      }
    },
    deleteOrg () {
      if (this.orgInfo) {
        const params = {}
        params.orgId = this.orgInfo.orgId
        setTimeout(() => {
          this.$http.post(deleteOrg,params).then(() => {
            modal.info({ title: '成功提示', content: '删除成功' })
            const data = [...this.orgList]
            loop(data, this.orgInfo.orgId, (item, index, arr) => {
              arr.splice(index, 1)
            })
            this.orgList = data
            this.selectedKeys = []
            this.orgInfo = null
            this.infoButtonType = '9'
            this.$refs.orgPage.setInitDate(null)
            this.$refs.orgPage.getOrgTreeByType()
            this.$refs.orgPage.getOrgSelectTree()
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要删除的数据' })
      }
    },
    onDragEnter (info) {
      console.log(info)
      // expandedKeys 需要受控时设置
      // this.expandedKeys = info.expandedKeys
    },
    onDrop (info) {
      console.log(info)
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const params = {}
      params.dropKey = dropKey
      params.dragKey = dragKey
      params.dropPosition = dropPosition
      setTimeout(() => {
        this.$http.post(moveOrg,params).then((res) => {
          const data = [...this.orgList]
          // Find dragObject
          let dragObj
          loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1)
            dragObj = item
          })
          if (!info.dropToGap) {
            // Drop on the content
            loop(data, dropKey, item => {
              item.children = item.children || []
              // where to insert 示例添加到尾部，可以是随意位置
              item.children.push(dragObj)
            })
          } else if (
            (info.node.children || []).length > 0 && // Has children
            info.node.expanded && // Is expanded
            dropPosition === 1 // On the bottom gap
          ) {
            loop(data, dropKey, item => {
              item.children = item.children || []
              // where to insert 添加到第一行
              item.children.unshift(dragObj)
            })
          } else {
            let ar
            let i
            loop(data, dropKey, (item, index, arr) => {
              ar = arr
              i = index
            })
            if (dropPosition === -1) {
              ar.splice(i, 0, dragObj)
            } else {
              ar.splice(i + 1, 0, dragObj)
            }
          }
          this.orgList = data
          this.orgInfo = res.result
          this.$refs.orgPage.setInitDate(res.result)
        }).catch(() => {
        })
      }, 50)
    },
    clearOrgCache () {
      const params = {}
      if (this.orgInfo) {
        params.orgId = this.orgInfo.orgId
      }
      setTimeout(() => {
        this.$http.post(clearOrgCache,params).then(() => {
          modal.info({ title: '成功提示', content: '清除缓存成功' })
        }).catch(() => {
        })
      }, 100)
    },
    handleUserPageChange ({ currentPage, pageSize }) {
      this.userTablePage.pageNum = currentPage
      this.userTablePage.currentPage = currentPage
      this.userTablePage.pageSize = pageSize
      this.findUserList()
    },
    handleRolePageChange ({ currentPage, pageSize }) {
      this.roleTablePage.pageNum = currentPage
      this.roleTablePage.currentPage = currentPage
      this.roleTablePage.pageSize = pageSize
      this.findRoleList()
    },
    openRoleModel () {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        const params = {}
        params.orgId = this.selectedKeys[0]
        this.roleVisible = true
        setTimeout(() => {
          this.$http.post(getOrgRoleInfo,params).then((res) => {
            this.$refs.roleTransferPage.setDataSource(res.result.roleList)
            this.$refs.roleTransferPage.setTargetKeys(res.result.targetKeys)
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要授权的数据' })
      }
    },
    saveRole () {
      const checkedRoles = this.$refs.roleTransferPage.roleTargetKeys
      const orgId = this.orgInfo.orgId
      const params = {}
      params.orgId = orgId
      params.roleIds = checkedRoles
      setTimeout(() => {
        this.$http.post(saveOrgRole,params).then(() => {
          modal.info({ title: '成功提示', content: '保存成功' })
          this.findRoleList()
          this.roleVisible = false
        }).catch(() => {
        })
      }, 50)
    },
    checkMethod ({ row }) {
      // 勾选框是否可操作
      const privilegeSource = row.privilegeSource
      if (privilegeSource === 'alone') {
        return true
      } else {
        return false
      }
    },
    openOrgUserModel () {
      // 打开添加用户页面
      if (this.orgInfo) {
        this.orgUservisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的组织' })
      }
    },
    saveUser () {
      const users = this.$refs.orgUserPage.userChecked
      const orgId = this.orgInfo.orgId
      if (users) {
        if (users.length <= 0) {
          modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
          return false
        }
      } else {
        modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
        return false
      }
      const userIds = []
      users.forEach((item) => {
        userIds.push(item.userId)
      })
      const params = {}
      params.orgId = orgId
      params.userIds = userIds
      setTimeout(() => {
        this.$http.post(saveOrgUser,params).then(() => {
          modal.info({ title: '成功提示', content: '授权成功' })
          this.orgUservisible = false
          this.findUserList()
        }).catch(() => {
        })
      }, 10)
    },
    deleteUser () {
      if (this.orgInfo) {
        const checkedUser = this.$refs.userListTable.getCheckboxRecords()
        const selectReserveRecords = this.$refs.userListTable.getCheckboxReserveRecords()
        const userIds = []
        if (checkedUser && checkedUser.length > 0) {
          checkedUser.forEach((item) => {
            userIds.push(item.userId)
          })
        }
        if (selectReserveRecords && selectReserveRecords.length > 0) {
          selectReserveRecords.forEach((item) => {
            userIds.push(item.userId)
          })
        }
        if (userIds.length > 0) {
          const params = {}
          params.userIds = userIds
          params.orgId = this.orgInfo.orgId
          setTimeout(() => {
            this.$http.post(deleteOrgUser,params).then(() => {
              modal.info({ title: '成功提示', content: '删除成功' })
              this.findUserList()
            }).catch(() => {
            })
          }, 10)
        } else {
          modal.warn({ title: '提示', content: '请先勾选需要删除的用户' })
        }
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的组织' })
      }
    },
    clearUserAll () {
      this.queryUserParam = {}
      this.findUserList()
      setTimeout(() => {
        this.$refs.userListTable.clearSelection()
        this.$refs.userListTable.clearSelectReserve()
      }, 50)
    },
    clearRoleAll () {
      this.queryRoleParam = {}
      this.findRoleList()
      setTimeout(() => {
        this.$refs.roleListTable.clearSelection()
        this.$refs.roleListTable.clearSelectReserve()
      }, 50)
    }
  }
}
</script>
<style lang="less" scoped>
@import "~ant-design-vue/lib/style/themes/default.less";
.search-tree-color {
  color : @primary-color
}
</style>
